import React, { PureComponent } from 'react'
import { connect } from 'dva'
import { Card, Form, Input, Table, Row, Col, Button, Tooltip } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import settings from '@/../config/defaultSettings'
import styles from './Index.less'
import PropModal from './PropModal'
import AOEForm from './AOEForm'

const FormItem = Form.Item

@connect(({ loading, approve }) => ({
  approve,
  loading: loading.models.approve,
}))
@Form.create()
export default class Approve extends PureComponent {
  // 组件加载完成后加载数据
  componentDidMount() {
    const { dispatch } = this.props
    dispatch({
      type: 'approve/fetchList',
    })
  }

  // 重置事件
  handleFormReset = () => {
    const { form, dispatch } = this.props
    form.resetFields()
    dispatch({
      type: 'approve/fetchList',
    })
  }

  // 搜索事件
  handleSearch = e => {
    e.preventDefault()

    const { form, dispatch } = this.props
    // 表单验证
    form.validateFields((err, fieldsValue) => {
      if (err) return

      const values = {
        ...fieldsValue,
      }

      dispatch({
        type: 'approve/fetchList',
        payload: values,
      })
    })
  }

  // 资产明细 弹框
  handlePropsClick = async (record, e) => {
    e.preventDefault()
    const { dispatch } = this.props
    try {
      const typeObj = {
        1: 'items', // 资产报废
        2: 'items', // 资产转移
        3: 'items', // 资产报修
        4: 'zcList', // 资产盘点
      }
      await dispatch({
        type: 'approve/updateState',
        payload: {
          showProps: true,
        },
      })
      await dispatch({
        type: 'approve/fetchProps',
        payload: {
          id: record.id,
          current: 1,
          size: 1000,
          dataKey: typeObj[record.type],
        },
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 处理审批 弹框
  handleApprove = (record, e) => {
    const { dispatch } = this.props
    e.preventDefault()
    dispatch({
      type: 'approve/updateState',
      payload: {
        showApproveModal: true,
        currentItem: record,
      },
    })
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.approve
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      ...formValues,
      current: pg.current,
    }

    dispatch({
      type: 'approve/fetchList',
      payload: params,
    })
  }

  renderSearchForm = () => {
    const { loading } = this.props
    //
    const { getFieldDecorator } = this.props.form
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={24} sm={24}>
            <FormItem label="*审批名称">
              {getFieldDecorator('approveReason')(
                <Input placeholder="请输入" maxLength={settings.inputMaxLength} />,
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 15 }}>
          <div style={{ marginLeft: 'auto' }}>
            <Button type="primary" htmlType="submit" loading={loading}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} loading={loading}>
              重置
            </Button>
          </div>
        </div>
      </Form>
    )
  }

  // 渲染界面
  render() {
    const { loading, dispatch } = this.props
    const { list, pagination, showProps, showApproveModal } = this.props.approve

    const columns = [
      {
        title: '审批单号',
        align: 'center',
        dataIndex: 'orderNo',
        width: 200,
        sorter: (a, b) => a.orderNo && a.orderNo.localeCompare(b.orderNo),
        sortDirections: ['descend', 'ascend'],
      },
      {
        title: '审批内容明细',
        align: 'center',
        width: 150,
        sorter: (a, b) => a.approveReason && a.approveReason.localeCompare(b.approveReason),
        sortDirections: ['descend', 'ascend'],
        render: (text, record) => (
          <div>
            <a onClick={e => this.handlePropsClick(record, e)}>{record.approveReason}</a>
          </div>
        ),
      },
      {
        title: '审批类型',
        align: 'center',
        dataIndex: 'typeStr',
        width: 80,
      },
      {
        title: '审批提交日期',
        align: 'center',
        dataIndex: 'gmtCreateStr',
        width: 100,
      },
      {
        title: '前序审批人',
        align: 'center',
        width: 80,
        render: (text, record) => <div>{record.createUsersEntity.realityName}</div>,
      },
      {
        title: '审批完成时间',
        align: 'center',
        dataIndex: 'gmtModifyStr',
        width: 100,
      },
      {
        title: '状态',
        align: 'center',
        width: 80,
        dataIndex: 'statusStr',
        render: (text, record) => {
          if (record.status === '0000') {
            return (
              <Tooltip title={record.remark || ''}>
                <a>{record.statusStr}</a>
              </Tooltip>
            )
          }
          return record.statusStr
        },
      },
      {
        title: '操作',
        align: 'center',
        width: 80,
        render: (text, record) => {
          if (record.status === '0001') {
            return (
              <div>
                <a onClick={e => this.handleApprove(record, e)}>审批</a>
              </div>
            )
          }
        },
      },
    ]

    const propModalProps = {
      showModal: showProps,
      modalCloseCallback: () => {
        dispatch({
          type: 'approve/updateState',
          payload: {
            showProps: false,
          },
        })
      },
    }
    const AOEFormProps = {
      showModal: showApproveModal,
      modalConfirmCallback: values => {
        dispatch({
          type: 'approve/consent',
          payload: values,
        })
      },
      modalCloseCallback: () => {
        dispatch({
          type: 'approve/updateState',
          payload: {
            showApproveModal: false,
          },
        })
      },
    }
    return (
      <PageHeaderWrapper title="待审批申请">
        <div className={styles.goodsInfoList}>
          <div className={styles.goodsInfoListForm}>
            <Card className={styles.noPadding} bordered={false}>
              {this.renderSearchForm()}
            </Card>
            <Card style={{ marginTop: 15 }} className={styles.noPadding} bordered={false}>
              <Table
                loading={loading}
                size="small"
                bordered
                dataSource={list}
                rowKey={record => record.id}
                pagination={pagination}
                columns={columns}
                onChange={this.handleListChange}
              />
            </Card>
          </div>
        </div>
        <PropModal {...propModalProps}></PropModal>
        {showApproveModal && <AOEForm {...AOEFormProps}></AOEForm>}
      </PageHeaderWrapper>
    )
  }
}
